window.onload = function () {
    const { createEditor, createToolbar } = window.wangEditor

    const editorConfig = {
        placeholder: 'Type here...',
        onChange(editor) {
            const html = editor.getHtml()
            console.log('editor content', html)
            // 也可以同步到 <textarea>
        },
    }

    const editor = createEditor({
        selector: '#editor-container',
        html: '<p><br></p>',
        config: editorConfig,
        mode: 'default', // or 'simple'
    })

    const toolbarConfig = {}

    const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    })

    $("#submit-btn").click(function (event) {
        console.log('Button clicked');
        // 阻止默认提交行为
        event.preventDefault();
        let title = $("input[name='title']").val();
        let category = $("#category-select").val();
        let content = editor.getHtml();
        
        let csrfToken = $("input[name='csrfmiddlewaretoken']").val();
        $.ajax('/blog/pub', {
            method: 'POST',
            data: {title: title, category: category, content: content, csrfmiddlewaretoken: csrfToken},
            success: function (response) {
                if (response.code === 200) {
                    // 获取博客id
                    let blogId = response.data.blog_id;
                    // 跳转到博客详情页
                    window.location = '/blog/' + blogId;
                } else {
                    alert(response.message);
                    console.error(response.errors);
                }
            }
        })
    })
}